define(['./../../directive/imgAddOn'], function () {
    var app = angular.module('App.home');
    app.controller('projects.detail.statusCtrl', ['$http', '$scope', '$timeout', 'curPrj', 'PrjStatus', 'prjStatusList', 'showMsg',
        'showInfoModal',
        function ($http, $scope, $timeout, curPrj, PrjStatus, prjStatusList, showMsg, showInfoModal) {
            // 获取工况列表
            $scope.prjStatusList = prjStatusList;

            // 上传插件
            $scope.item = new PrjStatus(curPrj.prjId);
            var plupload;
            var imgPrefix = "1200w_900h_50q_";
            var initUploader = function () {
                var uploader = Qiniu.uploader({
                    runtimes: 'html5,flash,html4', // 上传模式，依次退化
                    browse_button: 'imgUpload', // 上传选择的点选按钮，**必需**
                    uptoken_url: '/token',
                    unique_names: true,
                    domain: 'http://7i7il6.com1.z0.glb.clouddn.com/',
                    container: 'container', // 上传区域DOM ID，默认是browser_button的父元素
                    max_file_size: '100mb', // 最大文件体积限制
                    flash_swf_url: 'javascripts/bin/plupload/Moxie.swf', // 引入flash，相对路径
                    max_retries: 3, // 上传失败最大重试次数
                    dragdrop: false, // 开启可拖拽上传
                    chunk_size: '4mb', // 分块上传时，每片的体积
                    auto_start: false, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
                    init: {
                        'FilesAdded': function (up, files) {
                            for (var i = 0; i < files.length; i++) {
                                $scope.$apply(function () {
                                    $scope.item.StatusImgs.push({
                                        PrjId: curPrj.prjId,
                                        Date: $scope.item.Date.toString(),
                                        Url: '',
                                        Description: '',
                                        file: files[i],
                                        uploadFinish: false,
                                        key: '',
                                        originKey: '',
                                        percent: '0%',
                                        isEditOld: false
                                    });
                                });
                            }
                        },
                        'BeforeUpload': function (up, file) {
                            var index = findIndex(file);
                            var img = $('#img' + index);
                            img.addClass('upload-image');
                            img.css({
                                'display': 'block'
                            });
                        },
                        'UploadProgress': function (up, file) {
                            var index = findIndex(file);
                            var pp = file.percent + '%';
                            var img = $('#img' + index);
                            img.find('.bar').first().css({
                                'width': pp
                            });
                        },
                        'FileUploaded': function (up, file, info) {
                            var domain = up.getOption('domain');
                            var index = findIndex(file);
                            info = JSON.parse(info);
                            $scope.item.StatusImgs[index].originKey = info.key;
                            $scope.item.StatusImgs[index].key = imgPrefix + info.key;
                            $scope.item.StatusImgs[index].Url = domain + $scope.item.StatusImgs[index].key;
                            // 触发压缩程序
                            $http({
                                method: 'post',
                                url: '/imageCompress',
                                data: {
                                    key: $scope.item.StatusImgs[index].key,
                                    originKey: info.key
                                }
                            }).success((function (ii) {
                                return function (data) {
                                    if (data.toString() === 'false') {
                                        console.log('压缩失败');
                                    }
                                };
                            })(index));

                            if (index === $scope.item.StatusImgs.length - 1) {
                                // 剔除没有URL的工况图片
                                $scope.item.StatusImgs = $scope.item.StatusImgs.filter(function (item) {
                                    return item.Url.length > 0;
                                });
                                // 队列文件处理完毕后，处理相关的事情
                                var alReady = $scope.prjStatusList.filter(function (item) {
                                    return item.Date === $scope.item.Date;
                                });
                                if (alReady.length > 0) { // 如果是更新已有的工况，先删除已有列表中的工况
                                    $scope.alreadyIndex = $scope.prjStatusList.indexOf(alReady[0]);
                                    $scope.prjStatusList.splice($scope.alreadyIndex, 1);
                                    curPrj.statusList = $scope.prjStatusList;
                                } else {
                                    $scope.alreadyIndex = -1;
                                }
                                uploadStatusItem();
                            }
                        },
                        'Error': function (up, err, errTip) {
                            alert('上传图片出错，刷新页面再试！');
                        },
                        'UploadComplete': function () {

                        }
                    }
                });
                return uploader;
            };

            function uploadStatusItem() {
                curPrj
                    .postStatus($scope.item)
                    .then(function (success) {
                        if (success) {
                            if ($scope.alreadyIndex >= 0) {
                                curPrj.statusList.splice($scope.alreadyIndex, 0, $scope.item);
                            } else {
                                curPrj.statusList.push($scope.item);
                            }
                            showMsg('上传成功!', 'info');
                            $scope.prjStatusList = curPrj.statusList;
                            $scope.item = new PrjStatus(curPrj.prjId); // 重新初始化一下工况选项
                        }
                    });
            }
            var findIndex = function (file) {
                var index = -1;
                for (var i = 0; i < $scope.item.StatusImgs.length; i++) {
                    if ($scope.item.StatusImgs[i].file === file) {
                        index = i;
                    }
                }
                return index;
            };
            // 移除某图片
            $scope.removeImage = function (index) {
                $scope.item.StatusImgs.splice(index, 1);
            };
            // 提交工况
            $scope.confirm = function () {
                if (!$scope.item.Date || !$scope.item.Title || !$scope.item.Detail) {
                    showInfoModal({
                        title: '参数不完整',
                        content: '请按照指定的要求完整填写,再点击提交!',
                        scope: $scope
                    });
                } else {
                    //有图片
                    if ($scope.item.StatusImgs.length > 0) {
                        plupload.start();
                    } else { //没图片
                        uploadStatusItem();
                    }
                }
            };

            // 修改历史工况
            $scope.setCurItem = function (index) {
                $scope.item = angular.copy($scope.prjStatusList[index], $scope.item);
                $scope.item.IsEditOld = true;
                $scope.item.StatusImgs.forEach(function (item) {
                    item.isEditOld = true;
                });
            };

            // 新增工况
            $scope.add = function () {
                $scope.item = new PrjStatus(curPrj.prjId);
            };

            // 删除工况
            $scope.delete = function () {
                if ($scope.prjStatusList.length === 0)
                    return;
                var selectedList = $scope.prjStatusList.filter(function (item, index, array) {
                    return item.Selected === true;
                });
                var selectedDateList = selectedList.map(function (item) {
                    return item.Date;
                });
                if (selectedDateList.indexOf($scope.item.Date) >= 0)
                    $scope.item = new PrjStatus(curPrj.prjId);
                curPrj
                    .deleteStatus(selectedDateList)
                    .then(function () {
                        selectedList.forEach(function (item) {
                            var index = $scope.prjStatusList.indexOf(item);
                            $scope.prjStatusList.splice(index, 1);
                        });
                    });
            };

            $timeout(function () {
                plupload = initUploader();
            }, 500); // 初始化上传插件
        }
    ]);
});
